package mx.com.mindbits.bandpay.utils;

import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;


import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

public class HTTPConnector {
	private InputStream inputStream = null;
	private DataOutputStream printWriter = null;
	private int readTimeOut; 
	private int connectionTimeOut; 
	private String returnResponse = "";
	private StringBuilder parametros; 
	private String UTF8_ENCODE = "UTF-8";
	private int codeServerError;
	
	public int getReadTimeOut() {
		return readTimeOut;
	}

	public void setReadTimeOut(int readTimeOut) {
		this.readTimeOut = readTimeOut;
	}

	public int getConnectionTimeOut() {
		return connectionTimeOut;
	}

	public void setConnectionTimeOut(int connectionTimeOut) {
		this.connectionTimeOut = connectionTimeOut;
	}
	
	public HTTPConnector(){
		setReadTimeOut(ConstantsValues.READ_TIME_OUT);
		setConnectionTimeOut(ConstantsValues.CONNECTION_TIME_OUT);
		parametros = new StringBuilder();
		codeServerError = ConstantsValues.CODE_SERVER_ERROR;
	}

	public boolean checkConnection(Context contexto){		
		ConnectivityManager connManager = 
				(ConnectivityManager) contexto.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
		if(networkInfo != null && networkInfo.isConnected()){
			return true;
		}else{
			return false;
		}
	}//checkConnection
	
	public String connectToURL(String URLParam, String param) throws IOException{
		try{
			parametros.append("json=").append(URLEncoder.encode(param, UTF8_ENCODE));
			URL newURL = new URL(URLParam);
			HttpURLConnection conn 	= (HttpURLConnection) newURL.openConnection();			
			conn.setReadTimeout(readTimeOut);
			conn.setConnectTimeout(connectionTimeOut);			
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Accept-Charset", UTF8_ENCODE);
			conn.addRequestProperty("Content-Type","application/x-www-form-urlencoded");
			conn.addRequestProperty("Content-Length",""+Integer.toString(parametros.toString().getBytes().length));
			conn.setDoInput(true);
			conn.setDoOutput(false);
			conn.setUseCaches(false);
			
			printWriter = new DataOutputStream(conn.getOutputStream());
			printWriter.writeBytes(parametros.toString());
			printWriter.close();
			printWriter.flush();
			codeServerError = conn.getResponseCode();
			
			if(codeServerError != HttpURLConnection.HTTP_OK){
				inputStream = conn.getErrorStream();
				Log.e(ConstantsValues.TAG_UTILS, "ERROR UNO: "+inputStream);
				returnResponse = "SIN DATOS...";
			}else{
				inputStream = conn.getInputStream();
				Log.d(ConstantsValues.TAG_UTILS, "EXITO: "+inputStream);
				returnResponse = readStream (inputStream,ConstantsValues.LENGTH_STREAM);
				Log.i(ConstantsValues.TAG_TAEFORM, "return response = " + returnResponse );
			}									
			//printWriter.close();
			
			
		}catch(Exception e){
			Log.d(ConstantsValues.TAG_UTILS,"CHECANDO: "+URLParam);
			Log.e(ConstantsValues.TAG_UTILS,"ERROR DOS: "+e);
		}
		finally{
			if(inputStream != null){
				inputStream.close();
			}
			if(printWriter != null){
				printWriter.close();
			}			
		}
		return returnResponse;
	}
	
	public String readStream(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
	    Reader reader = null;
	    reader = new InputStreamReader(stream, "UTF-8");        
	    char[] buffer = new char[len];
	    reader.read(buffer);
	    return new String(buffer);
	}

}
